package pers.ervinse.shoppingmall.user.fragment;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.bumptech.glide.Glide;

import pers.ervinse.shoppingmall.R;
import pers.ervinse.shoppingmall.api.RetrofitClient;
import pers.ervinse.shoppingmall.domain.User;
import pers.ervinse.shoppingmall.domain.Res;  // 用于处理后端返回的结果
import pers.ervinse.shoppingmall.domain.realUser;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;


public class changeUserInfoActivity extends AppCompatActivity {

    private EditText edtUserName, edtEmail;
    private RadioGroup rgSex;
    private RadioButton rbMale, rbFemale;
    private ImageView ivAvatar;
    private Button btnSave;
    private ProgressDialog progressDialog;

    private String avatarUrl;  // 当前头像地址
    private int userId;  // 用户ID（假设从登录页面或本地存储传递过来）

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_change_user_info);

        // 获取传递过来的用户数据
        Intent intent = getIntent();
        userId = intent.getIntExtra("userId", -1);
        avatarUrl = intent.getStringExtra("avatarUrl");

        // 初始化控件
        edtUserName = findViewById(R.id.edtUserName);
        edtEmail = findViewById(R.id.edtEmail);
        rgSex = findViewById(R.id.rgSex);
        rbMale = findViewById(R.id.rbMale);
        rbFemale = findViewById(R.id.rbFemale);
        ivAvatar = findViewById(R.id.ivAvatar);
        btnSave = findViewById(R.id.btnSave);

        // 设置头像
        Glide.with(this)
                .load(avatarUrl)
                .circleCrop()
                .into(ivAvatar);

        // 设置默认值（假设从登录数据传递过来）
        edtUserName.setText(intent.getStringExtra("userName"));
        edtEmail.setText(intent.getStringExtra("email"));
        int sex = intent.getIntExtra("sex", 0);  //  0 为女性，1 为男性
        if (sex == 1) {
            rbMale.setChecked(true);
        } else {
            rbFemale.setChecked(true);
        }

        // 保存按钮点击事件
        btnSave.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                saveUserInfo();
            }
        });
    }

    private void saveUserInfo() {
        String userName = edtUserName.getText().toString().trim();
        String email = edtEmail.getText().toString().trim();
        int sex = rbMale.isChecked() ? 1 : 0;

        // 检查用户名和邮箱是否为空
        if (TextUtils.isEmpty(userName) || TextUtils.isEmpty(email)) {
            Toast.makeText(this, "用户名或邮箱不能为空", Toast.LENGTH_SHORT).show();
            return;
        }

        // 显示加载对话框
        progressDialog = ProgressDialog.show(this, "保存", "正在保存...", true, false);

        // 创建User对象
        realUser updatedUser = new realUser(userId, userName, null, sex, email, avatarUrl);

        // 使用Retrofit发送更新请求
        Call<Res> call = RetrofitClient.getApiService().updateUser(updatedUser);
        call.enqueue(new Callback<Res>() {
            @Override
            public void onResponse(Call<Res> call, Response<Res> response) {
                progressDialog.dismiss();
                if (response.isSuccessful() && response.body() != null && response.body().isSuccess()) {
                    Toast.makeText(changeUserInfoActivity.this, "用户信息更新成功", Toast.LENGTH_SHORT).show();
                    finish();
                } else {
                    Toast.makeText(changeUserInfoActivity.this, "更新失败，请稍后重试", Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Call<Res> call, Throwable t) {
                progressDialog.dismiss();
                Toast.makeText(changeUserInfoActivity.this, "网络请求失败，请稍后重试", Toast.LENGTH_SHORT).show();
            }
        });
    }
}
